//
//  QianMainWindowVC.swift
//  todoios
//
//  Created by qianli on 2025/4/10.
//

import Foundation
import UIKit
import NetworkExtension

import SwiftyUserDefaults
import Yams

//https://github.com/jpsim/Yams

//import UserNotifications

//import Moya
//Moya也定义了Task与Swift的Task冲突，如果需要Moya的话，可以指定一个别名： @_exported import Moya.Task as MoyaTask
//或者用Swift.Task调用系统的Task

class QianMainWindowVC: UIViewController {
    
    lazy var notiScrollview: UIScrollView = {
        let notiscroll = UIScrollView()
        notiscroll.showsHorizontalScrollIndicator = false
        notiscroll.isPagingEnabled = false
        return notiscroll
    }()
    private var UqAS86qhF6MO2qDs:UIImageView?
    private var UvnSrEZdlWgSzFxe:UILabel?
    private var tyi3SLYBCWAwDLmg:UILabel?
    private var dfFqf7hBPASzo0Z0:UIImageView?
    
    private var gqAAt48D69O3eb0V:UIImageView?
    private var Im8hl8CBwbpUKkwa:UILabel?
    
    private var WxmDIff590WooeX0:UIImageView?
    private var FTwvmVmSUdJmGcaO:UILabel?
    
    private let Z8yLNtonDaZXZoo5 = QianliVpnManager.shared
    private var _runningState:NEVPNStatus = .invalid //真实状态
    private var _mineView: MineView?
    private var _loadingHud:MBProgressHUD?
    private var _timer: Timer?
    private var _alertBgView:UIView?
    private var _buyGuideView:UIView?
    private var _notiView:UIView?
    
    private var fRVVGw2kqKYNKJzW: Timer?
    
    private lazy var retryView:RetryNet = {
        let tmpView = RetryNet()
        return tmpView
    }()
    
    private var zzSlxOdRaR1Kvn6l:Int = 0
    
    private var PFZ9JkPXYYqB6INF:String?
    
    private var MuX3f02rCYJlfDJM:Bool = false
    
    private var MRXkpv4MdQ01tlAa:Bool = false
    
    private var OxzatoShfU2CxhHp = false
    
    private var B89aanLUu6mcvcTH = false
    
    
    
    deinit {//奇怪，在viewDidLoad初始化过程中，会触发一次deinit，而退出App时反而不会触发
        QianliUniversalFunc.QianliLog("------MainVC.deinit")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        pbFvmqx1Lb2Ifgs0()
        iyDeSaPKCzr5f6dG()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.MRXkpv4MdQ01tlAa = true
        
        oN0G5xzbIHJAiKYz()
        
        self.nMdvDNRCpHe9Om0N()
        self.zQvadXwaQRV67JmE()
        
//判断有udid时，才启用
        let token = Defaults[\.token]
        if (!token.isEmpty){
            if Defaults[\.hasAllowedPolicy]{
                self.vOzKzS2HbOHZpSez("")
            }
            self.perform(#selector(Gqb3bbCfe165tG09), with: nil, afterDelay: 0.5)
        }

        Task{
            await self.A4bDBrPKJfZfzjr7()
        }
        
    }
    
    func RD3vN6W3P2Jlmxlm(){
        self.view.backgroundColor = .secondarySystemBackground //UIColor.init("#F6F6FA")
//        print("systemGroupedBackground:",UIColor.systemGroupedBackground.hexString!) //线色模式：#F2F2F7，深色模式：#000000
//        print("systemBackground:",UIColor.systemBackground.hexString!)//线色模式：#FFFFFF，深色模式：#000000
//        print("secondarySystemBackground:",UIColor.secondarySystemBackground.hexString!)//线色模式：#F2F2F7，深色模式：#1C1C1E
    }

    func pbFvmqx1Lb2Ifgs0(){
//        qianli_workarea_top //375*265
        let bgHeight = qianli_pm_width/375.0 * 265.0
        let topBgView = UIImageView(frame: CGRect(x: 0, y: 0, width: qianli_pm_width, height: bgHeight))
        self.view.addSubview(topBgView)
        topBgView.image = "qianli_workarea_top".qianli_R_image
        
        let iTopJG = 10.0
        let iOKHeight = 36.0
        let topSpace = UIDevice.qianli_statusbar_and_navibar_height()
        let titleBarHeight = iTopJG+iOKHeight
        let topbarView = UIView(frame: CGRect(x: 0, y: topSpace-titleBarHeight, width: qianli_pm_width, height: titleBarHeight))
        view.addSubview(topbarView)
        
        let label = UILabel(frame: CGRect(x: 100, y: 0, width: qianli_pm_width-200 , height: titleBarHeight))
        topbarView.addSubview(label)
        label.numberOfLines = 0
        label.textColor = .label
        label.font = .boldSystemFont(ofSize: 18)
        label.text = LocalizedString("Qianli Accelerator")
        label.textAlignment = .center
    
        let iBtnWidth = titleBarHeight
        let menuBtn = UIButton(frame: CGRect(x: 15, y: 0, width: iBtnWidth, height: titleBarHeight))
//        menuBtn.setTitle("我的", for: .normal)
//        menuBtn.setImage("qianli_slider_menu".qianli_R_image, for: .normal)
        menuBtn.qianli_button_image(image: "qianli_slider_mine".qianli_R_image,imgSize: CGSize(width: 32, height: 32))
        topbarView.addSubview(menuBtn)
        menuBtn.touch_With_Block {[weak self] sender in
//显示提示，必须同意才能继续使用
            QianliVibrateEnum.light.L4smXfL531Hmh91R()
            self?.TVJayEZRhev0NNT8("showMineView")
        }
        
        let btnKefu = UIButton(frame: CGRect(x: qianli_pm_width-15-iBtnWidth, y: 0, width: iBtnWidth, height: titleBarHeight))
        btnKefu.setTitle(LocalizedString("LINKUS"), for: .normal)
        let btnForeColor = UIColor.init(51, 102, 255)
        btnKefu.setTitleColor(btnForeColor, for: .normal)
        btnKefu.qianli_button_image(image: "qianli_slider_item_5".qianli_R_image,imgSize: CGSize(width: 24, height: 24),imgPadding: 3, imgColor: btnForeColor, imagePlacement: .top, font: .systemFont(ofSize: 8))
        topbarView.addSubview(btnKefu)
        btnKefu.touch_With_Block {sender in
//显示提示，必须同意才能继续使用
            QianliVibrateEnum.light.L4smXfL531Hmh91R()
            QianliUniversalFunc.PqHXCLMrbGaK2xN1(QianliConfig.CUSTOMER_SUPPORT) { success in
            }
        }
        
//加速工作区
        let imgWidth = qianli_pm_width - 60
        if let image = "qianli_workarea_bg".qianli_R_image {
            let imgHeight = imgWidth * (image.size.height / image.size.width)
            var imgcenter = CGPoint(x: 0, y: 0)
            self.UqAS86qhF6MO2qDs = UIImageView(frame: CGRect(x: 30, y: topSpace + 88, width: imgWidth, height: imgHeight))
            
            if let backImgView = self.UqAS86qhF6MO2qDs{
                backImgView.image = image
                view.addSubview(backImgView)
                imgcenter = backImgView.center
            }
            
            let btnWidth = 200.0
            let mainButton = UIButton(frame: CGRect(origin: CGPoint(x: imgcenter.x - btnWidth/2,y: imgcenter.y - btnWidth/2), size: CGSize(width: btnWidth, height: btnWidth)))
            view.addSubview(mainButton)
            mainButton.setBackgroundImage(UIColor("#3366FF").image(), for: .normal)
            mainButton.setBackgroundImage(UIColor("#5588FF").image(), for: .highlighted)
            mainButton.layer.cornerRadius = btnWidth/2
            mainButton.layer.borderWidth = 3.0
            mainButton.layer.borderColor = UIColor.white.cgColor
            mainButton.clipsToBounds = true // setBackgroundImage后，需要裁剪视图，不然光cornerRadius还是方角
//            mainButton.setTitle("开启运行", for: .normal)
            mainButton.tag = 1000 //表示未启动状态
            mainButton.touch_With_Block{ [weak self] (sender)   in
                QianliVibrateEnum.selection.L4smXfL531Hmh91R()
                self?.tRr0UHTQJ6Ofh0ze()
            }
            
            let btnLogoWidth = 50.0
            self.dfFqf7hBPASzo0Z0 = UIImageView(image: "qianli_start_speed".qianli_R_image)
            if let icoView = self.dfFqf7hBPASzo0Z0{
                mainButton.addSubview(icoView)
                icoView.frame = CGRect(x: btnWidth/2 - btnLogoWidth/2, y:btnWidth/2 - btnLogoWidth+5, width: btnLogoWidth, height: btnLogoWidth)
            }
            
            self.UvnSrEZdlWgSzFxe = UILabel(frame: CGRect(x: 10, y: btnWidth/2+15, width: btnWidth-20, height: 24))
            if let btnLabel = self.UvnSrEZdlWgSzFxe{
                mainButton.addSubview(btnLabel)
                btnLabel.font = .boldSystemFont(ofSize: 18)
                btnLabel.textColor = .white
                btnLabel.text = LocalizedString("START")
                btnLabel.textAlignment = .center
            }
            
            self.tyi3SLYBCWAwDLmg = UILabel(frame: CGRect(x: 15, y: btnWidth-55, width: btnWidth-30, height: 20))
            if let timeLabel = self.tyi3SLYBCWAwDLmg{
                mainButton.addSubview(timeLabel)
                timeLabel.font = UIFont(name: "Courier", size: 12)//等宽Font
                timeLabel.textColor = .white
                timeLabel.text = "00:00:00"
                timeLabel.textAlignment = .center
                timeLabel.isHidden = true
            }
        }
//底部节点
//底部会呗
        let viewSpace = 40.0
        let nodeView = UIView(frame: CGRect(x: viewSpace, y: qianli_pm_height-220, width: qianli_pm_width-viewSpace*2, height: 60))
        view.addSubview(nodeView)
        nodeView.layer.cornerRadius = 16
        nodeView.backgroundColor = .systemBackground
        nodeView.tap_With_Block {[weak self] in
            QianliVibrateEnum.selection.L4smXfL531Hmh91R()
            self?.TVJayEZRhev0NNT8("showCountryPage")
        }
        let logoHeight = 40.0 * 4.0 / 6.0
        self.gqAAt48D69O3eb0V = UIImageView(frame: CGRect(x: 15, y: 60/2 - logoHeight/2, width: 40, height: logoHeight))
        if let imgView = self.gqAAt48D69O3eb0V{
            nodeView.addSubview(imgView)
            imgView.image = "qianli_flag_auto".qianli_R_image
//            imgView.clipsToBounds = true
//            imgView.layer.cornerRadius = 10
//            imgView.layer.borderColor = UIColor.secondarySystemBackground.cgColor
//            imgView.layer.borderWidth = 0.1
        }
        self.Im8hl8CBwbpUKkwa = UILabel(frame: CGRect(x: 65, y: 10, width: nodeView.bounds.width-15-13, height: 40))
        if let label = self.Im8hl8CBwbpUKkwa{
            nodeView.addSubview(label)
            label.textColor = .label
            label.font = .systemFont(ofSize: 16)
            label.text = LocalizedString("Auto Best Router")
        }
        let arrowNode = UIImageView(frame: CGRect(x: nodeView.bounds.width-15-8, y: nodeView.bounds.height/2-8, width: 8, height: 16))
        nodeView.addSubview(arrowNode)
        arrowNode.image = "qianli_row_more".qianli_R_image
        
        let vipView = UIView(frame: CGRect(x: viewSpace, y: qianli_pm_height-140, width: qianli_pm_width-viewSpace*2, height: 60))
        view.addSubview(vipView)
        vipView.layer.cornerRadius = 16
        vipView.backgroundColor = UIColor("#3366FF")
        vipView.tap_With_Block { [weak self]  in
            QianliVibrateEnum.selection.L4smXfL531Hmh91R()
            self?.TVJayEZRhev0NNT8("showMemberPage")
        }
        self.WxmDIff590WooeX0 = UIImageView(frame: CGRect(x: 15, y: 10, width: 40, height: 40))
        if let imgView = self.WxmDIff590WooeX0{
            vipView.addSubview(imgView)
            imgView.image = "qianli_member_bar".qianli_R_image
        }
        self.FTwvmVmSUdJmGcaO = UILabel(frame: CGRect(x: 65, y: 10, width: vipView.bounds.width-15-13, height: 40))
        if let label = self.FTwvmVmSUdJmGcaO{
            vipView.addSubview(label)
            label.textColor = .white
            label.font = .systemFont(ofSize: 16)
        }
        self.yYkse4BscAVs9i6z()
        let arrowVip = UIImageView(frame: CGRect(x: vipView.bounds.width-15-8, y: vipView.bounds.height/2-8, width: 8, height: 16))
        vipView.addSubview(arrowVip)
        arrowVip.image = "qianli_row_member".qianli_R_image
        
        let kefuBtn = UIButton(frame: CGRect(x: qianli_pm_width-80, y: qianli_pm_height-300, width: 80, height: 35))
        view.addSubview(kefuBtn)
        kefuBtn.setTitle(LocalizedString("LINK US"), for: .normal)
        kefuBtn.setTitleColor(.label, for: .normal)
        kefuBtn.titleLabel?.font = .systemFont(ofSize: 13)
        kefuBtn.backgroundColor = .systemBackground.withAlphaComponent(0.6)
//        kefuBtn.layer.borderWidth = 0.5
//        kefuBtn.layer.borderColor = UIColor.lightGray.cgColor
        kefuBtn.qianli_round_rect(corner: [.topLeft,.bottomLeft], radii: CGSize(width: 20, height: 20))
        kefuBtn.touch_With_Block { sender in
            let customUrl = Defaults[\.customerURL]
            QianliUniversalFunc.PqHXCLMrbGaK2xN1(customUrl) { success in
            }
        }
        
        
    }
    
    func M411Z6QRn2UIecUa(msg:String){
//滚动轮播消息
        func xudc9nNU3BDAu6kX(){
            if (_timer != nil){
                _timer?.invalidate()
            }
            _timer = nil
        }
        
        func t49qf1QknFcTe4d3() {
            if (_timer != nil){
                xudc9nNU3BDAu6kX()
            }
            _timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(W1zioxnir62Ns0OV), userInfo: nil, repeats: true)
        }
        
        func oi1xERlm0cVbY6oc(){
            if let notiView = _notiView{
                notiScrollview.removeFromSuperview()
                for perView in notiView.subviews {
                    perView.removeFromSuperview()
                }
                notiView.removeFromSuperview()
            }
            _notiView=nil
        }
        
        xudc9nNU3BDAu6kX();
        
        if (msg.isEmpty){
            oi1xERlm0cVbY6oc()
            return
        }
        
        let iOKHeight = 40.0
        
        let label = UILabel()
        if(_notiView == nil){
            let topSpace = UIDevice.qianli_statusbar_and_navibar_height()
            _notiView = UIView(frame: CGRect(x: 15, y: topSpace+20, width: qianli_pm_width-30, height: iOKHeight))
            if let notiview = _notiView{
                if let mineview = _mineView{
                    view.insertSubview(notiview, belowSubview: mineview)
                }else{
                    view.addSubview(notiview)
                }
                notiview.backgroundColor = .systemBackground
                notiview.layer.cornerRadius = 12 //iOKHeight/2.0
                notiview.tap_With_Block {[weak self] in
                    self?.WCnCM9MqiBsSupjA()
                }
                
                let imgView = UIImageView(image: "qianli_broad_noti".qianli_R_image)
                notiview.addSubview(imgView)
                imgView.frame = CGRect(x: 10, y: iOKHeight/2 - 24/2, width: 24, height: 24)
                
                notiview.addSubview(self.notiScrollview)
                notiScrollview.frame = CGRect(x: 44, y: iOKHeight/2 - 24/2, width: notiview.bounds.width - 44 - 10, height: 24)
                notiScrollview.addSubview(label)
                label.textColor = UIColor.init(51, 102, 255) // .label
                label.font = UIFont.systemFont(ofSize: 15)
                label.sizeToFit()
            }
        }
//轮播msg，根据msg，更新scrollView的content长度等
//        "尊敬的用户：\n你好，五一优惠已上新啦，欢迎积极参与优惠活动（手机端参与），希望五一假日期间能开开心心地安全享受全球网络，祝各位节日快乐~"
        label.text =  msg.replacingOccurrences(of: "\n", with: " ") //存在有换行符的情况
        label.sizeToFit()//必须在label.text赋值后再执行一次
        label.frame = CGRect(x: 0, y: (notiScrollview.bounds.height - label.bounds.height) / 2, width: label.bounds.width, height: label.bounds.height)
        notiScrollview.contentSize = CGSize(width: label.bounds.width, height: notiScrollview.bounds.height)
        t49qf1QknFcTe4d3()
        
        if !self.OxzatoShfU2CxhHp{
//本次启动，首次显示通知弹窗
            let lastDate = Defaults[\.lastArticleAlertDate]
            let daysPassed = Calendar.current.dateComponents([.day], from: lastDate, to: Date()).day ?? 0
            if daysPassed >= 3{//从 3 月 1 日到 3 月 3 日，中间间隔 2 天 ,daysPassed=2
                WCnCM9MqiBsSupjA(true)
            }
        }
    }
    func TCjTJHl1iGUPjZHD(){
        _alertBgView?.isHidden = true
        if let alertbgview = _alertBgView{
            for perView in alertbgview.subviews{
                perView.removeFromSuperview()
            }
        }
        _alertBgView = nil
    }
    
    func WCnCM9MqiBsSupjA(_ isAuto:Bool = false){
        TCjTJHl1iGUPjZHD()
        
        let message = Defaults[\.notiArticleContent]
        let attributedMessage = NSMutableAttributedString(string: message)
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 8 // 设置行间距，可根据需要调整
        attributedMessage.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: message.count))
        attributedMessage.addAttributes([NSAttributedString.Key.foregroundColor: UIColor.secondaryLabel,//UIColor(hexString: "#3964ff"),
                                         NSAttributedString.Key.font:UIFont.systemFont(ofSize: 15)], range: NSRange(location: 0, length: message.count))
     
//        let alert = UIAlertController(title: Defaults[\.notiArticleTitle], message: nil, preferredStyle:.alert)
//        alert.setValue(attributedMessage, forKey: "attributedMessage")
////同理attributedTitle可以设置Alert的标题样式
////      alert.setValue(attributedTitle, forKey: "attributedTitle")
//        alert.addAction(UIAlertAction(title: "确定", style:.default, handler: nil))
//        present(alert, animated: true, completion: nil)
        _alertBgView = UIView(frame: CGRect(x: 0, y: 0, width: qianli_pm_width, height: qianli_pm_height))
        if let alertbgview = _alertBgView{
            self.view.addSubview(alertbgview)
            alertbgview.backgroundColor = .black.withAlphaComponent(0.6)
            
            let alertWidth = qianli_pm_width-40
            let alertView = UIView(frame: CGRect(x: 20, y: qianli_pm_height/2-200, width: alertWidth, height: 300))
            alertbgview.addSubview(alertView)
            alertView.backgroundColor = .secondarySystemBackground
            alertView.layer.cornerRadius = 12
            let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: alertWidth, height: 60))
            alertView.addSubview(titleLabel)
            titleLabel.text = Defaults[\.notiArticleTitle]
            titleLabel.textColor = .label
            titleLabel.font = .boldSystemFont(ofSize: 15)
            titleLabel.textAlignment = .center
            
            let txtView = UITextView(frame: CGRect(x: 15, y: titleLabel.bounds.height, width: alertWidth-30, height: 300-20-titleLabel.bounds.height))
            alertView.addSubview(txtView)
            txtView.textColor = .secondaryLabel
            txtView.backgroundColor = .secondarySystemBackground
            txtView.attributedText = attributedMessage
            txtView.isUserInteractionEnabled = true
            txtView.isEditable = false
            txtView.isSelectable = true //允许选择复制
            
//            txtView.layer.cornerRadius = 6
            
            if isAuto{
                let closeBtn = UIButton(frame: CGRect(x: qianli_pm_width-20-alertWidth/2+5, y: qianli_pm_height/2+120, width: alertWidth/2-5, height: 48))
                alertbgview.addSubview(closeBtn)
                closeBtn.setTitle(LocalizedString("Got it"), for: .normal)
                closeBtn.setTitleColor(.label, for: .normal) //UIColor(hexString: "#3762FF")
                closeBtn.backgroundColor = .secondarySystemBackground
                closeBtn.titleLabel?.font = .systemFont(ofSize: 14)
                closeBtn.qianli_round_rect(corner: [.allCorners], radii: CGSizeMake(6, 6))
                closeBtn.touch_With_Block {[weak self] sender in
                    self?.TCjTJHl1iGUPjZHD()
                }
                let closeBtn_2 = UIButton(frame: CGRect(x: 20, y: qianli_pm_height/2+120, width: alertWidth/2-5, height: 48))
                alertbgview.addSubview(closeBtn_2)
                closeBtn_2.setTitle(LocalizedString("Donot show again 3 days"), for: .normal)// "3天内不再显示"
                closeBtn_2.setTitleColor(.secondaryLabel, for: .normal)
                closeBtn_2.backgroundColor = .secondarySystemBackground
                closeBtn_2.titleLabel?.font = .systemFont(ofSize: 13)
                closeBtn_2.qianli_round_rect(corner: [.allCorners], radii: CGSizeMake(6, 6))
                closeBtn_2.touch_With_Block {[weak self] sender in
                    Defaults[\.lastArticleAlertDate] = Date()
                    self?.TCjTJHl1iGUPjZHD()
                }
            }else{
                let closeBtn = UIButton(frame: CGRect(x: alertbgview.bounds.width/2 - 30/2, y: qianli_pm_height/2+120, width: 30, height: 30))
                alertbgview.addSubview(closeBtn)
                closeBtn.setImage("qianli_alert_btclose".qianli_R_image, for: .normal)
                closeBtn.touch_With_Block {[weak self] sender in
                    self?.TCjTJHl1iGUPjZHD()
                }
            }
            
            alertbgview.isHidden = false
            self.OxzatoShfU2CxhHp = true
        }
    }
    
    @objc func W1zioxnir62Ns0OV() {
        let scrollSpeed: CGFloat = 50// 滚动速度，每秒滚动的点数
        let currentOffset = notiScrollview.contentOffset.x
        let newOffset = currentOffset + scrollSpeed * 0.01 // 根据时间和速度更新偏移量
        if newOffset >= notiScrollview.contentSize.width {
            // 消息末尾快消失时，迅速重置到起始位置
//            notiScrollview.contentOffset = .zero
//            而是回到显示区域的末尾开始拉进来
            notiScrollview.contentOffset = CGPoint(x: -notiScrollview.bounds.width+10, y: 0)
        } else {
            notiScrollview.contentOffset = CGPoint(x: newOffset, y: 0)
        }
    }
    
    func Z8oDVaZkZX9bE7wT(){
        if let mineview = _mineView{
//动画hide
            mineview.backgroundColor = .black.withAlphaComponent(0)
            UIView.animate(withDuration: 0.25, delay: 0,options: [.curveEaseInOut]) {[weak mineview] in
                mineview?.frame.origin.x = -qianli_pm_width//从右向左退出
            } completion: { [weak self] _ in
                if let mineVV = self?._mineView{
                    for perView in mineVV.subviews {
                        perView.removeFromSuperview()
                    }
                    mineVV.removeFromSuperview()
                }
                self?._mineView=nil
            }
        }else{
            _mineView = nil
        }
    }
    
    func zfhTjUtL6p1GIZ82(){
        self.l0JOXR3PG9RznwqZ()
        
        if _mineView == nil{
            let newMineView = MineView.init(frame: CGRect(x: -qianli_pm_width, y: 0, width: qianli_pm_width, height: qianli_pm_height))
            view.addSubview(newMineView)
            newMineView.closeBlock = {[weak self] in
                self?._mineView=nil
            }
            _mineView = newMineView
            _mineView?.tapBlock = { [weak self](itemindex) in
                if itemindex != 8{
                    self?.Z8oDVaZkZX9bE7wT()
                }
                
                switch itemindex {
                case 1:
                    QianliVibrateEnum.selection.L4smXfL531Hmh91R()
                    self?.TVJayEZRhev0NNT8("showCountryPage")
                    break
                case 2:
                    QianliVibrateEnum.selection.L4smXfL531Hmh91R()
                    let myOrderVC = QianliUserOrderlistVC()
                    myOrderVC.modalPresentationStyle = .overFullScreen
                    self?.present(myOrderVC, animated: true)
                    myOrderVC.dismissBlock = {[weak self] in
                        self?.vOzKzS2HbOHZpSez("")
                    }
                    break
                case 3:
                    QianliVibrateEnum.selection.L4smXfL531Hmh91R()
                    let refgxcVC = QianliRefgxfcCqqnbVC()
                    refgxcVC.modalPresentationStyle = .overFullScreen
                    self?.present(refgxcVC, animated: true)
                    refgxcVC.dismissBlock = {[weak self] in
                        self?.vOzKzS2HbOHZpSez("")
                    }
                case 4:
                    QianliVibrateEnum.selection.L4smXfL531Hmh91R()
                    let forgetVC = QianliNotforgetVC()
                    forgetVC.modalPresentationStyle = .overFullScreen
                    self?.present(forgetVC, animated: true)
                    forgetVC.dismissBlock = {[weak self] in
                        self?.vOzKzS2HbOHZpSez("")
                    }
                case 5:
//                  在线客服
                    QianliVibrateEnum.selection.L4smXfL531Hmh91R()
                    let customUrl = Defaults[\.customerURL]
                    QianliUniversalFunc.PqHXCLMrbGaK2xN1(customUrl) { success in
                    }
                case 6:
//                   公告
                    QianliVibrateEnum.selection.L4smXfL531Hmh91R()
                    let articleVC = QianliArticleVC()
                    articleVC.modalPresentationStyle = .overFullScreen
                    self?.present(articleVC, animated: true)
                    articleVC.dismissBlock = {[weak self] in
                        self?.vOzKzS2HbOHZpSez("")
                    }
                case 99:
                    QianliVibrateEnum.selection.L4smXfL531Hmh91R()
                    self?.TgeK4V7Y0X5oCBne()
                case 7,11:
                    QianliVibrateEnum.light.L4smXfL531Hmh91R()
                    if Defaults[\.isGuset]{
                        self?.oFj2xilmy7vogXsc()
                    }else{
                        let userDetail = QainliUserDetail()
                        userDetail.modalPresentationStyle = .overFullScreen
                        self?.present(userDetail, animated: true)
                        userDetail.dismissBlock = { [weak self] in
                            self?.yYkse4BscAVs9i6z()
//                            self?.vOzKzS2HbOHZpSez("")
                        }
                    }
                case 8:
                    QianliVibrateEnum.light.L4smXfL531Hmh91R()
                    self?.alert_qianli_sheet_message("", message: LocalizedString("Sure to Clear All Cahces?"), selections: [LocalizedString("SURE")], tapBlock: { actionIndex in
                        QianliUniversalFunc.sharedInstance.Tju6icGvNKLcvCiG()
                        self?._mineView?.PefGxtaeiGhiGKAO()
                    })
                case 90:
//                    registerButton
                    QianliVibrateEnum.selection.L4smXfL531Hmh91R()
                    self?.ph2lqG56246k5nHN()
                    
                case 91:
//                    loginButton
                    QianliVibrateEnum.selection.L4smXfL531Hmh91R()
                    self?.oFj2xilmy7vogXsc()
                default:
                    break
                }
            }
        }
        
        if let myView = _mineView{
            myView.frame = CGRect(x: -qianli_pm_width, y: 0, width: qianli_pm_width, height: qianli_pm_height)
            UIView.animate(withDuration: 0.25, delay: 0,options: [.curveEaseInOut]) {[weak self] in
                if let mineview = self?._mineView{
                    mineview.frame.origin.x = 0
                }
            }
        }
        
    }
}

extension QianMainWindowVC{
    private func ph2lqG56246k5nHN(){
        let registerVc = QianliUserRegisterVC()
        registerVc.modalPresentationStyle = .overFullScreen
        registerVc.registerOKBlock = {[weak self]mail,pw in
            if let self = self{
                self.X7vYe1QunkSRgBBp("")
            }
        }
        registerVc.doLoginBlock = {[weak self] in
            if let self=self{
                self.MuX3f02rCYJlfDJM = false
                self.oFj2xilmy7vogXsc()
            }
        }
        registerVc.dismissBlock = {[weak self] in
            if let self = self{
                self.yYkse4BscAVs9i6z()
                self.MuX3f02rCYJlfDJM = false
            }
        }
        self.present(registerVc, animated: true)
        self.MuX3f02rCYJlfDJM = true
    }
    
    private func X7vYe1QunkSRgBBp(_ msg:String){
        self.l0JOXR3PG9RznwqZ()
        
        if (msg.isEmpty){
            LoginViewModel.shared.isLogouted = false
            self.view.Qianli_Toast(LocalizedString("Loading succeeded, enjoy it!"))
            self.yYkse4BscAVs9i6z()
            self.MuX3f02rCYJlfDJM = false
            self.vOzKzS2HbOHZpSez("")
        }else{
            self.view.Qianli_Toast(msg)
        }
    }
    
    private func UWRdl1krZEkBno2y(){
        let loginVc = QainliUserLoginVC()
        loginVc.modalPresentationStyle = .overFullScreen
        loginVc.loginOKBlock = {[weak self] in
        //登录成功后，要更新详情信息
            if let self = self{
                DispatchQueue.main.async {
                    self.view.Qianli_Toast(LocalizedString("Login Success!"))
                }
            }
        }
        self.present(loginVc, animated: true)
    }
    
}

extension QianMainWindowVC{
    @objc func Gqb3bbCfe165tG09(){
        let iPageNum = 1
        let filed_1 = FieldParamsList(condition: "=", conditionValue: "1", field: "status", fieldType: "", fieldParamsListOperator: "")
        let filed_2 = FieldParamsList(condition: "=", conditionValue: "notice", field: "type", fieldType: "", fieldParamsListOperator: "AND")
        let fieldParamsList = [filed_1,filed_2]
        let arequest = AnnouncementRequest(fieldParamsList: fieldParamsList, pagination: Pagination(orderBy: "id DESC", pageNum: iPageNum, pageSize: 1), select: "", tableName: "article")
        UserInfoViewModel.shared.a6MH0MGhx9xhDERm(announcementRequest: arequest) { result in
            DispatchQueue.main.async {[weak self]  in
                switch result{
                case .failure(let error):
                    self?.KBqIKQ9HAzT2WzdD(error.localizedDescription)
                case .success(let baseData):
                    if baseData.code == 0{
                        self?.KBqIKQ9HAzT2WzdD("")
                    }else{
                        self?.KBqIKQ9HAzT2WzdD("[\(baseData.code)]\(baseData.msg)")
                    }
                }
            }
        }
//        UserInfoViewModel.shared.completionMsgHandler = {[weak self](result,msg) in
//            DispatchQueue.main.async {
//                self?.KBqIKQ9HAzT2WzdD(msg)
//            }
//        }
    }
    
    func KBqIKQ9HAzT2WzdD(_ result:String){
        if(result.isEmpty){
            if let articleData = UserInfoViewModel.shared.articleResultData{
                if (articleData.total>0){
                    if let myArticleList = articleData.data{
                        if(myArticleList.count>0){
                            Defaults[\.notiArticleContent] = myArticleList[0].content
                            Defaults[\.notiArticleTitle] = myArticleList[0].title
                            self.M411Z6QRn2UIecUa(msg: Defaults[\.notiArticleContent])
                            return
                        }
                    }
                }
            }
//数据为空,说明不需要广播，则置空并停止
            Defaults[\.notiArticleContent] = ""
            Defaults[\.notiArticleTitle] = ""
            M411Z6QRn2UIecUa(msg: "")
        }else{
            M411Z6QRn2UIecUa(msg: Defaults[\.notiArticleContent])
        }
    }
    
}

extension QianMainWindowVC{
    private func tRr0UHTQJ6Ofh0ze(){
//        let arr = [1,2,3,4]
//        print(arr[5])  //test.do: crash
        
        if _runningState == .connected{
//准备断开
            jmq6IgOvJbVksBNk()
        }else if _runningState == .disconnected || _runningState == .invalid{
//准备开启
            Defaults[\.lastQianliStartDate] = 0
            TVJayEZRhev0NNT8("startProxy")
        }else{
            self.view.Qianli_Toast(LocalizedString("Processing,Please wait..."),delayTime: 1.0)
        }
    }
    
    private func nMdvDNRCpHe9Om0N(){
        self.Z8yLNtonDaZXZoo5.uc134OWEq85miEpc {[weak self] status in
            switch(status) {
            case .connecting,.reasserting:
                print("readyProxy>PNStatus: connecting")
                self?._runningState = .connecting
                break
            case .connected:
                print("readyProxy>PNStatus: connected")
                self?._runningState = .connected
                break
            case .disconnecting:
                print("readyProxy>PNStatus: disconnecting")
                self?._runningState = .disconnecting
                break
            case .disconnected:
                print("readyProxy>PNStatus: disconnected")
                self?._runningState = .disconnected
                break
            default:
                print("readyProxy>PNStatus: unknown")
                self?._runningState = .invalid
                break
            }
            DispatchQueue.main.async {[weak self] in
                self?.oBh2hlVFZ9s5Cgka()
            }
        }

    }
    
    private func A8tW2HCNHpyKoNzc(_ isConnected:Bool,_ is2Fore:Bool){
        if self.UqAS86qhF6MO2qDs?.tag != 1001 || is2Fore{
            if let backImgView = self.UqAS86qhF6MO2qDs{
                backImgView.stop_qianli_ripple_animate()
                if isConnected{
                    backImgView.tag = 1001 //表示已创建
                    let rippleSize = CGSize(width: backImgView.bounds.width/2, height: backImgView.bounds.width/2)
                    let rippleColor = UIColor.secondaryLabel.withAlphaComponent(0.5)
                    backImgView.start_qianli_ripple_animate(rippleSize: rippleSize, position: CGPoint(x: backImgView.bounds.width/2, y: backImgView.bounds.height/2), color: rippleColor, duration: CFTimeInterval(1.0),repeatCount: Float.infinity)
                }
            }
        }
        
    }

    private func oBh2hlVFZ9s5Cgka(){
        if let alabel = self.UvnSrEZdlWgSzFxe,let aimageView = self.dfFqf7hBPASzo0Z0{
            switch(_runningState) {
            case .connecting:
                alabel.text = LocalizedString("STARTING")
                aimageView.qianli_image(imgurl: "qianliLoading.gif")
                break
            case .connected:
                alabel.text = LocalizedString("RUNNING")//加速中
                aimageView.image = "qianli_stop_speed".qianli_R_image
                break
            case .disconnecting:
                alabel.text = LocalizedString("STOPPING")  //"正在断开"
                aimageView.qianli_image(imgurl: "qianliLoading.gif")
                break
            case .disconnected,.invalid:
                alabel.text = LocalizedString("START") //"开启加速"
                aimageView.image = "qianli_start_speed".qianli_R_image
                break
            default:
                print("PNStatus: unknown")
                break
            }
            
        }
        
        if _runningState == .connected{
            //显示雷达动画
             A8tW2HCNHpyKoNzc(true,false)
            
            let lastInterval = Defaults[\.lastQianliStartDate]
            if lastInterval == 0{
                //如果为空，则开始计时，不为空，说明已经开始计时，只需更新时间即可
                self.IQcpUUJINpPyE5Gb()
            }else{
                self.feZMYC8LMPCfHkeY()
            }
        }
        else if(_runningState == .disconnected || _runningState == .invalid){
            self.gKYhtPoiW44r45Cr()
            Defaults[\.lastQianliStartDate] = 0
            
            if let backImgView = self.UqAS86qhF6MO2qDs,backImgView.tag == 1001{
                backImgView.tag = 1000
                backImgView.stop_qianli_ripple_animate()
            }
            
            if let timealabel = self.tyi3SLYBCWAwDLmg{
                timealabel.text = "00:00:00"
                timealabel.isHidden = true
            }
            self.nar5y2MWT6mkH64S()
            
        }
        
    }
    
    private func GS5kUWN1jA1BD3sl() async {
        DispatchQueue.main.async {[weak self] in
            if let self = self{
                self.l0JOXR3PG9RznwqZ()
                Task{
                    do {
                        try await self.Z8yLNtonDaZXZoo5.aYrafiM1uaq29ytv()
                        try await Task.sleep(nanoseconds: 100_000_000) // 0.1s
                        let controller = await self.Z8yLNtonDaZXZoo5.M3Ll8cXUeFZ1dQDX()
                        if let controller = controller {
                            try await Task.sleep(nanoseconds: 100_000_000) // 0.1s
                            print("controller.PGNwXGR8GAQEZEdY")
                            try await controller.PGNwXGR8GAQEZEdY()
                        }
                    } catch {
                        print("startProxy.err:", error)
                    }
                }
                let content = Defaults[\.notiArticleContent]
                if content.isEmpty{
                    self.Gqb3bbCfe165tG09()
                }
            }
            
        }
    }
    
    private func jmq6IgOvJbVksBNk(){
        if let vpnController = self.Z8yLNtonDaZXZoo5.controller{
            vpnController.bMPPOBDIQcRES5Dc()
        }else{ //如果不是从App关闭、开启VPN，此回到App vpnManager.controller = nil
            Task{
                if let vpnController = await self.Z8yLNtonDaZXZoo5.M3Ll8cXUeFZ1dQDX(){
                    vpnController.bMPPOBDIQcRES5Dc()
                }
            }
        }
    }
    
    private func A4bDBrPKJfZfzjr7() async{
        await self.Z8yLNtonDaZXZoo5.y4On03TpAsKs4W4W(msg: "hello")
        
        switch(self.Z8yLNtonDaZXZoo5.controller?.connectionStatus) {
        case .connecting,.reasserting:
            print("queryProxy>PNStatus: connecting")
            _runningState = .connecting
            break
        case .connected:
            print("queryProxy>PNStatus: connected")
            _runningState = .connected
            break
        case .disconnecting:
            print("queryProxy>PNStatus: disconnecting")
            _runningState = .disconnecting
            break
        case .disconnected:
            print("queryProxy>PNStatus: disconnected")
            _runningState = .disconnected
            break
        default:
            print("queryProxy>PNStatus: unknown")
            _runningState = .invalid
            break
        }
        oBh2hlVFZ9s5Cgka()
    }
    
    private func nar5y2MWT6mkH64S(){
        NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(S536tRQ5zEaWCnwj), object: nil)
        self.perform(#selector(S536tRQ5zEaWCnwj), with: nil, afterDelay: 2.0)
    }
    
    @objc private func S536tRQ5zEaWCnwj(){
        Qianli_G_SharedMdb.shared.reload() //必须要重新load一下才能取到
        let errmsg = Qianli_G_SharedMdb.shared.GetHexinErr()
        print("------notiVpnErr>\(errmsg)")
        if !errmsg.isEmpty{
            ZacollectModel.shared.vnveDBhaItvpywSl("PacketTunnel", errmsg)
            Qianli_G_SharedMdb.shared.SetHexinErr(err: "")
        }
        
    }
    
//    func Qjg7R0nPbZpx7j5y(){ //test.do
////        let testStr = testfuncName
////        print("testStr>",testStr)
//    }
    
    private func gKYhtPoiW44r45Cr(){
        self.fRVVGw2kqKYNKJzW?.invalidate()
        self.fRVVGw2kqKYNKJzW = nil
        if let timeLabel = self.tyi3SLYBCWAwDLmg{
            timeLabel.isHidden = true
        }
    }
    
    private func IQcpUUJINpPyE5Gb(){
        if self.fRVVGw2kqKYNKJzW == nil,let timeLabel = self.tyi3SLYBCWAwDLmg{
            Defaults[\.lastQianliStartDate] = Date().timeIntervalSince1970
            // 每秒钟更新一次
            self.fRVVGw2kqKYNKJzW = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
                self?.HvX6JFtSSlzt271Z()
            }
            //立即显示初始值
            timeLabel.text = "00:00:00"
            timeLabel.isHidden = false
        }
    }
    
    private func feZMYC8LMPCfHkeY(){
        if self.fRVVGw2kqKYNKJzW == nil,_runningState == .connected,let timeLabel = self.tyi3SLYBCWAwDLmg{
            // 每秒钟更新一次
            self.fRVVGw2kqKYNKJzW = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
                self?.HvX6JFtSSlzt271Z()
            }
            // 立即更新一次
            timeLabel.isHidden = false
            self.HvX6JFtSSlzt271Z()
        }
    }
    
    private func HvX6JFtSSlzt271Z(){
        if let timeLabel = self.tyi3SLYBCWAwDLmg{
            if let startTime = o6Pf9xKZjIVWmMLh(){
                let elapsedTime = Date().timeIntervalSince(startTime)
                timeLabel.text = xhwtkpjQU1sXafXi(from: elapsedTime)
            }
        }
    }
    
    // 从UserDefaults获取VPN启动时间
   private func o6Pf9xKZjIVWmMLh() -> Date? {
       var timeInterval = Defaults[\.lastQianliStartDate]
       if timeInterval == 0{
           timeInterval = Date().timeIntervalSince1970
       }
       return Date(timeIntervalSince1970: timeInterval)
   }
    
    // 时间格式化
    private func xhwtkpjQU1sXafXi(from interval: TimeInterval) -> String {
        let hours = Int(interval) / 3600
        let minutes = (Int(interval) % 3600) / 60
        let seconds = Int(interval) % 60
        
        return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
    }
}

extension QianMainWindowVC{
    
    private func jmpifKA44gyyu3lE(subdir:String) -> URL {
        let documentsDirectory = FileManager.default.urls(for:.documentDirectory, in:.userDomainMask).first!
        // 获取应用文档目录(file:///var/mobile/Containers/Data/Application/xxxx/Documents/)
        let destDirectory = documentsDirectory.appendingPathComponent(subdir)
        // 主目录(file:///var/mobile/Containers/Data/Application/xxx/Documents/subdir)
        do {
            if !FileManager.default.fileExists(atPath: destDirectory.path) {
                try FileManager.default.createDirectory(at: destDirectory, withIntermediateDirectories: true, attributes: nil)
            }
        } catch {
            print("Failed to create directory: \(error.localizedDescription)")
            ZacollectModel.shared.vnveDBhaItvpywSl("PacketTunnel", "Failed to create directory: \(error.localizedDescription)")
        }
        return destDirectory //path = destDirectory.path
    }
}

extension QianMainWindowVC{
    func yYkse4BscAVs9i6z(){
        if let label = self.FTwvmVmSUdJmGcaO{
            let username = Defaults[\.username]
            let iso8601String = Defaults[\.memberexpiryat]
            if (username.isEmpty || iso8601String.isEmpty){
                label.text = LocalizedString("UNLOGIN")
            }else{
                label.text = isoDate2Formatdate(iso8601String) + " \(LocalizedString("EXPIRE"))"
            }
        }
    }
    
    func oTWYxpyvn2XC2AWP(){
        if let mineview = _mineView{
            mineview.uieXcVRJzNjKLXPF()
        }
    }
    
    func TgeK4V7Y0X5oCBne(){
        self.l0JOXR3PG9RznwqZ()
        
        let memberVC = QianliMemberVC()
        memberVC.modalPresentationStyle = .overFullScreen
        self.present(memberVC, animated: true)
        memberVC.dismissBlock = {[weak self] in
            if let self=self{
                self.yYkse4BscAVs9i6z()
                self.vOzKzS2HbOHZpSez("")
            }
        }
    }
    
    func flM9woQKzM3ymMZp(_ errMsg:String){
        self.l0JOXR3PG9RznwqZ()
        jmq6IgOvJbVksBNk()
        
        let deviceId = getDeviceID()
        UserInfoViewModel.shared.ofuUSDfMhcfgsObm(deviceId: deviceId) { _ in
            Defaults[\.token] = "" //只要响应都清除
        }
        QianliVpnManager.shared.controller?.bMPPOBDIQcRES5Dc()
        Defaults[\.username] = ""
        Defaults[\.avatar] = ""
        Defaults[\.memberexpiryat] = ""
        Defaults[\.invitationCode] = ""
        Defaults[\.memberLevel] = 0
        Defaults[\.isGuset] = true
        Defaults[\.isTester] = false
        Defaults[\.subuuid] = ""
        Defaults[\.maxBindCount] = 2
        
        LoginViewModel.shared.isLogouted = true
        UserInfoViewModel.shared.userDeviceList = nil
        Qianli_G_SharedMdb.shared.SetQianliHealthState(health: "")
        mnMPBDuqzrr59PAC()
        
        self.yYkse4BscAVs9i6z()
        
        self.alert_qianli_message(LocalizedString("Friendly Reminder"), message: "\(errMsg)\n\(LocalizedString("Please login again!"))") {[weak self] in
            if let self=self{
                self.oFj2xilmy7vogXsc()
            }
        }
        
    }
    
    private func mnMPBDuqzrr59PAC(){
        removeUuidYaml()
        Qianli_G_SharedMdb.shared.SetSubUUID(uuid: "")
    }
}

extension QianMainWindowVC{
    func uPJoek6ybNz2kTSg(){
        UserInfoViewModel.shared.getUserInfo { Result in
            DispatchQueue.main.async {[weak self] in
                switch Result{
                case .success(let baseData):
                    if let self = self{
                        if baseData.code == 0{
                            self.yYkse4BscAVs9i6z()
                            self.oTWYxpyvn2XC2AWP()
                            self.vQX9J2drzNqEKEyx()
                        }else if baseData.code == 40101{
                            self.flM9woQKzM3ymMZp(baseData.msg)
                        }
                    }
                case .failure(let err):
                    print("getUserInfo>Fail: \(err.localizedDescription)")
                }
            }
        }
    }
    
    func vQX9J2drzNqEKEyx(){
        //如果tester为true，上传全部信息，定时上传全部warning信息
    }
}


extension QianMainWindowVC{
//首次启动，因为无网络连接，导致各项数据读取不到，显示
    func PBw1Iq57b3Be0LKP(_ time:TimeInterval){
        self.perform(#selector(a8PKVW0O8SiZSm0H), with: nil, afterDelay: time)
    }
    
    @objc func a8PKVW0O8SiZSm0H(){
        let hasAllowed = Defaults[\.hasAllowedPolicy]
        if !hasAllowed{
            print("handleFirstConnect>canel: not.allowed.policy")
            return
        }
        self.zzSlxOdRaR1Kvn6l += 1
        if (self.zzSlxOdRaR1Kvn6l>QianliConfig.SERVIER_URL.count){
            self.zzSlxOdRaR1Kvn6l = 0
            LoginViewModel.shared.url_JKou_Index = 0
            LoginViewModel.shared.url_JKou = QianliConfig.SERVIER_URL[0]
            Defaults[\.lastJKouUrlIndex] = LoginViewModel.shared.url_JKou_Index
            DispatchQueue.main.async { [weak self] in
                if let self=self{
                    self.l0JOXR3PG9RznwqZ()
                    self.view.Qianli_Toast(LocalizedString("Init Data time out，retry later.")) //"初始化数据超时，请稍候重试."
                }
            }
            return
        }
        
        if (!LoginViewModel.shared.isDarwined){
            LoginViewModel.shared.url_JKou_Index = self.zzSlxOdRaR1Kvn6l - 1
            if LoginViewModel.shared.url_JKou_Index>=0 && LoginViewModel.shared.url_JKou_Index<QianliConfig.SERVIER_URL.count{
                LoginViewModel.shared.url_JKou = QianliConfig.SERVIER_URL[LoginViewModel.shared.url_JKou_Index]
            }else{
                LoginViewModel.shared.url_JKou_Index = 0
                LoginViewModel.shared.url_JKou = QianliConfig.SERVIER_URL[0]
            }
            Defaults[\.lastJKouUrlIndex] = LoginViewModel.shared.url_JKou_Index
            print("handleFirstConnect>[\(LoginViewModel.shared.url_JKou_Index)]\(LoginViewModel.shared.url_JKou)")
        }
        
        TVJayEZRhev0NNT8("")
    }
    
    func TVJayEZRhev0NNT8(_ todo:String){
        self.l0JOXR3PG9RznwqZ()
        
        if !todo.isEmpty && LoginViewModel.shared.isLogouted{
            self.oFj2xilmy7vogXsc()//LocalizedString("Please Login!")
            return
        }
        if (!LoginViewModel.shared.isDarwined){
            zYQA7faERo2Oz8J1(msg: LocalizedString("Loading Data,Please wait...")) //正在初始化数据,请稍候...
            g9D1FjVDNl5v23hZ(todo) //1
        }else if (Defaults[\.token].isEmpty){
            if todo.isEmpty{
                zYQA7faERo2Oz8J1(msg: "")
            }else{
                zYQA7faERo2Oz8J1(msg: LocalizedString("Loading Account,Please wait...")) //正在加载用户信息,请稍候...
            }
            self.hGjX8eq4VS8XbR9i(todo)//2
        }else if (!todo.isEmpty){
            self.OaCcvGjl55cdoNgq(todo) //3
        }else{
            self.l0JOXR3PG9RznwqZ()
            self.uPJoek6ybNz2kTSg() //更新用户信息
        }
    }
    
    func OaCcvGjl55cdoNgq(_ toNext:String){
//sure：has.Token && getPublicString.Over
        if toNext.isEmpty{
            self.l0JOXR3PG9RznwqZ()
            self.perform(#selector(Gqb3bbCfe165tG09), with: nil, afterDelay: 0.5)//首次启动后游客登录成功后刷新通知
            return
        }
//重新拉取用户信息,并更新UI
        self.uPJoek6ybNz2kTSg()
        
        self.perform(#selector(Gqb3bbCfe165tG09), with: nil, afterDelay: 1.0)
        
        let lowTo = toNext.lowercased()
        if(lowTo == "showmineview"){
            zfhTjUtL6p1GIZ82()
        }else if lowTo == "showmemberpage"{
            TgeK4V7Y0X5oCBne()
            return
        }else if (lowTo == "startproxy"){
//需要加载订阅信息(以防过期)及节点信息
            vOzKzS2HbOHZpSez(toNext)
        }else if (lowTo == "showcountrypage"){
//            if _runningState == .connected{
//已经在连接了，就不需要再次拉取数据
                self.OdQ4QZH4IkFYy5fW()
//            }else{
//                vOzKzS2HbOHZpSez(toNext)
//            }
        }
    }
    
}

extension QianMainWindowVC{
    func g9D1FjVDNl5v23hZ(_ next2do:String){
        if !LoginViewModel.shared.isDarwined {
            LoginViewModel.shared.getPulicSetting {[weak self] result in
                DispatchQueue.main.async {
                    switch result{
                    case .success(let baseData):
                        if baseData.code == 0{
                            self?.TVJayEZRhev0NNT8(next2do) //next:login&getToken
                        }else{
                            print("getPulicSetting>fail: [\(baseData.code)]\(baseData.msg)")
                            self?.XCycCIMIhDJpjXrY(next2do,baseData.msg)
                        }
                    case .failure(let err):
                        print("getPulicSetting>err:\(err.localizedDescription)")
                        self?.XCycCIMIhDJpjXrY(next2do,err.localizedDescription)
                    }
                }
            }
        }
    }
    
    func XCycCIMIhDJpjXrY(_ todo:String,_ errMsg:String){
//域名失败进入轮循
        self.l0JOXR3PG9RznwqZ()
        LoginViewModel.shared.isDarwined = false //重试getPulicSetting，这个接口要么网络断开，要么域名失效，基本不会出现别的错误，
        self.PBw1Iq57b3Be0LKP(1.5) //第一步就失败则重试
    }
    
    func EUvl72O8S25PYzD1(_ todo:String=""){
        LoginViewModel.shared.guestLogin {[weak self] result in
            DispatchQueue.main.async {
                switch result{
                case .failure(let error):
                    self?.iQTfk8PjPLikwhie(todo, error.localizedDescription)
                case .success(let baseData):
                    if (baseData.code==0){
                        self?.yYkse4BscAVs9i6z()
                        self?.OaCcvGjl55cdoNgq(todo) //3
                    }else{
                        self?.iQTfk8PjPLikwhie(todo, baseData.msg)
                    }
                }
            }
        }
    }
    
    func iQTfk8PjPLikwhie(_ todo:String,_ errMsg:String){
        self.l0JOXR3PG9RznwqZ()
        self.oFj2xilmy7vogXsc(LocalizedString("Load Account Failed，Please Login!"))//加载用户信息失败，请先登录账号！
    }
    
    func oFj2xilmy7vogXsc(_ errMsg:String=""){
        if self.MuX3f02rCYJlfDJM{
            print("!!!已显示登录页面")
        }else{
            let loginvc = QainliUserLoginVC()
            loginvc.modalPresentationStyle = .overFullScreen
            if !errMsg.isEmpty{
                loginvc.drLNPcLilSQNLR0o(errMsg)
            }
            self.present(loginvc, animated: true)
            self.MuX3f02rCYJlfDJM = true
            
            loginvc.loginOKBlock = {
                DispatchQueue.main.async {[weak self] in
                    if let self = self{
                        self.view.Qianli_Toast(LocalizedString("Login Success!")) //"登录成功！"
                        self.yYkse4BscAVs9i6z()
                        self.MuX3f02rCYJlfDJM = false
                        self.vOzKzS2HbOHZpSez("")
                    }
                }
            }
            
            loginvc.autoLoginOKBlock = {
                DispatchQueue.main.async {[weak self] in
                    if let self = self{
                        self.view.Qianli_Toast(LocalizedString("Loading succeeded, enjoy it!"))
                        self.yYkse4BscAVs9i6z()
                        self.MuX3f02rCYJlfDJM = false
                        self.vOzKzS2HbOHZpSez("")
                    }
                }
            }
            
            loginvc.dismissBlock = {[weak self] in
                self?.MuX3f02rCYJlfDJM = false
            }
        }
    }
    
    func hGjX8eq4VS8XbR9i(_ todo:String=""){
//sure： Defaults[\.token].isEmpty)
        if LoginViewModel.shared.enableGuestRegister{
            self.EUvl72O8S25PYzD1() //没有用户登录信息时，尝试游客登录获取Token
        }else{
            //等着用户自行登录
            self.l0JOXR3PG9RznwqZ()
            self.oFj2xilmy7vogXsc()//"请先登录账号！"LocalizedString("Please Login!")
        }
    }
    
    func vOzKzS2HbOHZpSez(_ toNext:String){
        if !toNext.isEmpty{
            zYQA7faERo2Oz8J1(msg: "")
        }
        
        LoginViewModel.shared.getCustomerServiceList {result in
            DispatchQueue.main.async {[weak self]  in
                switch result{
                case .failure(let error):
                    let err = error as NSError
                    if err.code == 6{ //网络断开，或域名失效
                        self?.XCycCIMIhDJpjXrY("",err.localizedDescription)
                        self?.Luxmux9My4MAgvB7(toNext, LocalizedString("Load Failed. Please check network & try again!"))
                    }else{
                        self?.Luxmux9My4MAgvB7(toNext, error.localizedDescription)
                    }
                case .success(let baseData):
                    if baseData.code == 0{
                        self?.Luxmux9My4MAgvB7(toNext, "")
                    }else if baseData.code == 40101{
                        self?.flM9woQKzM3ymMZp(baseData.msg)
                    }else{
                        self?.Luxmux9My4MAgvB7(toNext, "[\(baseData.code)]\(baseData.msg)")
                    }
                }
            }
        } //判断订阅信息是否还有效(过期、流量超标、uuid有误等)
    }
    
    func Luxmux9My4MAgvB7(_ todo:String,_ errmsg:String){
        if errmsg.isEmpty{
            if let customerServiceData = LoginViewModel.shared.customerServiceData{
                let subStatus = customerServiceData.subStatus
                let serviceStatus = customerServiceData.serviceStatus
                Defaults[\.serviceStatus] = serviceStatus
                Defaults[\.subStatus] = subStatus
                let subUUID = Qianli_G_SharedMdb.shared.GetSubUUID()
                if(!serviceStatus){
                    self.ciKM4gvYkpPI52kY(todo, LocalizedString("Membership has expired. Go to renew!"))
                    //"会员已到期，请前往会员中心购买！"
                }else if(!subStatus){
                    self.ciKM4gvYkpPI52kY(todo, LocalizedString("Member traffic limit exceeded. Go to purchase more!"))
                    //"会员流量已超标，请前往会员中心购买！"
                }else if(subUUID.isEmpty){
                    self.l0JOXR3PG9RznwqZ()
                    self.view.Qianli_Toast(LocalizedString("Subscription expired. Please retry later!"))//"订阅信息失效，请稍后重试！"
                }else{
                    let serviceEndAt = customerServiceData.serviceEndAt
                    self.KdaN8kw2fiYbt0lk(todo,subUUID,serviceEndAt)
                }
            }else{
                self.l0JOXR3PG9RznwqZ()
                self.view.Qianli_Toast(LocalizedString("Load Subscription Failed. Please retry later!"))//"获取订阅信息失败，请稍后重试！"
            }
        }else{
            self.l0JOXR3PG9RznwqZ()
            self.view.Qianli_Toast(errmsg)
        }
    }
    
    func ciKM4gvYkpPI52kY(_ todo:String,_ errmsg:String){
        //会员过期或流量超标时的处理
        self.l0JOXR3PG9RznwqZ()
        self.ml2yurhJLXHYn8oT()
        if todo.lowercased() == "showcountrypage"{
            self.OdQ4QZH4IkFYy5fW()
        }else{
//            self.view.Qianli_Toast(errmsg)
            self.x9CmoecsxWMdHoaU(errmsg)
        }
    }
    
    func ml2yurhJLXHYn8oT(){
//关闭加速
        self.jmq6IgOvJbVksBNk()
//删除yaml
        removeUuidYaml()
    }
    
    func KdaN8kw2fiYbt0lk(_ nextDo:String,_ subUUID:String,_ serviceEndAt:String){
        self.l0JOXR3PG9RznwqZ()
        if nextDo.isEmpty{
            print("handle2GetNodeList>cancel:nextDo.is.Null")
            return
        }
        
        let cacheDir = jmpifKA44gyyu3lE(subdir: "cache")
        let cacheUrl = cacheDir.appendingPathComponent("config.yaml") //  "\(cacheDir)/config.yaml"
        self.zYQA7faERo2Oz8J1(msg: LocalizedString("Loading Proxy Node,Please wait..."))//"正在加载节点数据,请稍候..."
        
        let configUrl = createSubLink(subUUID: subUUID, isYaml: true)
        
        let urlstr = "\(LoginViewModel.shared.url_Yaml)\(configUrl)"
        let fileURL = URL(string: urlstr)!
        
        if let lasturl = self.PFZ9JkPXYYqB6INF,urlstr.lowercased() == lasturl.lowercased(){
            //说明本次启已经成功加载过，
            //而且target文件还存在，则不再下载，直接进行下一步即可
            //增加一个判断，serviceEndAt与本地一致才不需要下载,不然则需重新下载更新(后台改了结束日期，或会员升级了)
            if Defaults[\.serviceEndAt]  == serviceEndAt{
                h457wnSkPeo2D5E6()
                //判断target文件是否存，并且target文件的yaml格式是否正确，如果存在并正确，则不再重新下载
                if let target = Qianli_G_SharedMdb.shared.GetSharedFilePath(fileName: "config.yaml", uuid: subUUID){
                    if FileManager.default.fileExists(atPath: target.path){
                        if XYFZoC2UFgIZydai(target.path){
                            self.l0JOXR3PG9RznwqZ()
                            print("已存在有效yaml>continueNextWhenLoadAndExist")
                            YCMgSpdgNrF2b4sR(nextDo)
                            return
                        }
                    }
                }
            }
        }
        
        print("Load: \(fileURL)\nto:\(cacheUrl.path)")
        MoyaLoadfileModel.shared.downloadFile(url: fileURL, destinationPath: cacheUrl, completion: { [weak self] result in
            DispatchQueue.main.async { [weak self] in
                switch result {
                case .success(let cachFile):
                    Defaults[\.serviceEndAt] = serviceEndAt
                    print("文件下载成功，保存路径: \(cachFile)")
                    self?.Ct8AJwcg9FNeDCVo(nextDo, "", cachFile)
                case .failure(let error):
                    print("文件下载失败: \(error.localizedDescription)")
                    self?.Ct8AJwcg9FNeDCVo(nextDo,error.localizedDescription,nil)
                }
            }
        })
    }
    
    func Ct8AJwcg9FNeDCVo(_ nextDo:String,_ errmsg:String,_ cacheUrl:URL?){
        self.l0JOXR3PG9RznwqZ()
        if errmsg.isEmpty{
            if let cacheFile = cacheUrl{
                self.lKFfxxfcJMP6eSWP(src: cacheFile,todo: nextDo)
            }
        }else{
            if let cacheFile = cacheUrl,FileManager.default.fileExists(atPath: cacheFile.path){
                self.lKFfxxfcJMP6eSWP(src: cacheFile, todo: nextDo)
            }else{
                self.view.Qianli_Toast("\(LocalizedString("Proxy Node Load Failed"))：\(errmsg)") //加载节点配置失败
            }
        }
    }
    
    func YCMgSpdgNrF2b4sR(_ nextdo:String){
        self.l0JOXR3PG9RznwqZ()
        
        let lowto = nextdo.lowercased()
        if(lowto=="startproxy"){
            Task{
                await GS5kUWN1jA1BD3sl()
            }
            return
        }else if(lowto == "showcountrypage"){
            self.OdQ4QZH4IkFYy5fW()
        }
        else{
        //留待后续
        }
    }
    
    func h457wnSkPeo2D5E6(){
        if let mmdbUrl = Bundle.main.url(forResource: "Country", withExtension: "mmdb"){
            //Country.mmdb实际为ASN.mmdb，代码适配geoip.metadb\geoip.db\Country.mmdb三个文件，但文件不能过大，以免超限异常
            let _ = Qianli_G_SharedMdb.shared.TestCopyConfigToHomeUdidDir(configfile: mmdbUrl,uuid: "",replace: false)
        }
        if let mmdbUrl = Bundle.main.url(forResource: "geosite", withExtension: "dat"){
            let _ = Qianli_G_SharedMdb.shared.TestCopyConfigToHomeUdidDir(configfile: mmdbUrl,uuid: "",replace: false)
        }
        if let mmdbUrl = Bundle.main.url(forResource: "private", withExtension: "yaml"){
            let _ = Qianli_G_SharedMdb.shared.TestCopyConfigToHomeUdidDir(configfile: mmdbUrl,uuid: "ruleset",replace: false)
        }
        if let mmdbUrl = Bundle.main.url(forResource: "lancidr", withExtension: "yaml"){
            let _ = Qianli_G_SharedMdb.shared.TestCopyConfigToHomeUdidDir(configfile: mmdbUrl,uuid: "ruleset",replace: false)
        }
        if let mmdbUrl = Bundle.main.url(forResource: "cncidr", withExtension: "yaml"){
            let _ = Qianli_G_SharedMdb.shared.TestCopyConfigToHomeUdidDir(configfile: mmdbUrl,uuid: "ruleset",replace: false)
        }
        if let mmdbUrl = Bundle.main.url(forResource: "reject", withExtension: "yaml"){
            let _ = Qianli_G_SharedMdb.shared.TestCopyConfigToHomeUdidDir(configfile: mmdbUrl,uuid: "ruleset",replace: false)
        }
        if let mmdbUrl = Bundle.main.url(forResource: "alwaysdirect", withExtension: "yaml"){
            let _ = Qianli_G_SharedMdb.shared.TestCopyConfigToHomeUdidDir(configfile: mmdbUrl,uuid: "ruleset",replace: true)
        }
        if let mmdbUrl = Bundle.main.url(forResource: "applechina", withExtension: "txt"){
            let _ = Qianli_G_SharedMdb.shared.TestCopyConfigToHomeUdidDir(configfile: mmdbUrl,uuid: "ruleset",replace: true)
        }
        if let mmdbUrl = Bundle.main.url(forResource: "alibabaip", withExtension: "txt"){
            let _ = Qianli_G_SharedMdb.shared.TestCopyConfigToHomeUdidDir(configfile: mmdbUrl,uuid: "ruleset",replace: true)
        }
        if let mmdbUrl = Bundle.main.url(forResource: "cncdnip", withExtension: "txt"){
            let _ = Qianli_G_SharedMdb.shared.TestCopyConfigToHomeUdidDir(configfile: mmdbUrl,uuid: "ruleset",replace: true)
        }
        if let mmdbUrl = Bundle.main.url(forResource: "cndomain", withExtension: "txt"){
            let _ = Qianli_G_SharedMdb.shared.TestCopyConfigToHomeUdidDir(configfile: mmdbUrl,uuid: "ruleset",replace: true)
        }
        if let mmdbUrl = Bundle.main.url(forResource: "whatsappip", withExtension: "txt"){
            let _ = Qianli_G_SharedMdb.shared.TestCopyConfigToHomeUdidDir(configfile: mmdbUrl,uuid: "ruleset",replace: true)
        }
        
    }
    
    func lKFfxxfcJMP6eSWP(src:URL,todo:String){
        self.l0JOXR3PG9RznwqZ()
        
        //查看share.uuid下的配置文件在不在，如果不存在，则UI上提示，正在请求服务，请稍候；
        let uuid = Qianli_G_SharedMdb.shared.GetSubUUID()
        if uuid.isEmpty{
            self.view.Qianli_Toast(LocalizedString("Subscription expired. Please retry later!"))//加载订阅信息失效，请稍候重试
            ZacollectModel.shared.vnveDBhaItvpywSl("UnYamlFileToShare", "uuid为空")
            return
        }
        let lowto = todo.lowercased()
        let srcUrl = src
//        //test.do
//        if let configURL = Bundle.main.url(forResource: "config", withExtension: "yaml"){
//            srcUrl = configURL
//        }
//        //test.end
        let cachefile = srcUrl.path
        if XYFZoC2UFgIZydai(cachefile){
            //copy-cachfile2shared
            h457wnSkPeo2D5E6()
            
            if let target = Qianli_G_SharedMdb.shared.TestCopyConfigToHomeUdidDir(configfile: srcUrl,uuid: uuid,replace: true){
                if FileManager.default.fileExists(atPath: target.path){
//记录本次启动App后，下载的链接，如果再次打开加速，则不再重新下载
                    let configUrl = createSubLink(subUUID: uuid, isYaml: true)
                    self.PFZ9JkPXYYqB6INF = "\(LoginViewModel.shared.url_Yaml)\(configUrl)"
                    if(lowto=="startproxy"){
                        Task{
                            await GS5kUWN1jA1BD3sl()
                        }
                        return
                    }else if(lowto == "showcountrypage"){
                        self.OdQ4QZH4IkFYy5fW()
                        return
                    }
                }
            }
        }
        
        if (lowto == "startproxy" || lowto == "showcountrypage"){
            self.view.Qianli_Toast(LocalizedString("Proxy Node Load Failed,Please retry later"))//"节点数据加载失败，请稍候重试"
            ZacollectModel.shared.vnveDBhaItvpywSl("UnYamlFileToShare", "节点Yaml解析失败")
        }
    
    }
    
    func XYFZoC2UFgIZydai(_ yamlfile:String)->Bool{
        var iCount = 0
        print("hasValidProxyInYaml: \(yamlfile)")
        if  let yamlString = try? String(contentsOfFile: yamlfile) {
            do {
                let yaml = try Yams.load(yaml: yamlString) as! [String: Any]
                print("\(yaml)")
// proxy-groups下type=select的proxies节点组
                if let proxyGroups = yaml["proxy-groups"] as? [[String: Any]] {
                    for group in proxyGroups {
                        if let type = group["type"] as? String {
                            if type == "select"{
                                if let groupName = group["name"] as? String{
                                    Qianli_G_SharedMdb.shared.SetNodeGrop(groupName: groupName)
                                }
                                if let proxies = group["proxies"] as? [String]{
                                    iCount = proxies.count
                                }
                                break
                            }
//                            else if type == "url-test"{ //如果还是库里接口来healthcheck，则不需要了
//                                if let testUrl =  group["url"] as? String{
//                                    Defaults[\.nodetest] = testUrl
//                                }
//                            }
                        }
                    }
                }
                 
            }
            catch{
                iCount = 0
                print("hasValidProxyInYaml.err:\(error.localizedDescription)")
            }
        }
        
        return iCount>0
    }

    
}

extension QianMainWindowVC{
    func zYQA7faERo2Oz8J1(msg:String){
        DispatchQueue.main.async {[weak self] in
            if let self = self{
                self.l0JOXR3PG9RznwqZ()
                 
                self._loadingHud = MBProgressHUD.showAdded(to: self.view, animated: true)
                if let _loadingHud = self._loadingHud,!msg.isEmpty{
                    _loadingHud.label.text = msg
                }
            }
        }
    }
    
    private func l0JOXR3PG9RznwqZ(){
        if let loadingHud = _loadingHud{
            loadingHud.hide(animated: true)
        }
        _loadingHud?.isHidden = true
        _loadingHud = nil
    }
    
    private func x9CmoecsxWMdHoaU(_ msg:String){
        UZelDtHZwCXcTj32();
        let iSpace = 30.0
        let toastWidth = qianli_pm_width - iSpace*2
        let triangleHeight = 15.0
        let toastHeight = 80.0 + triangleHeight
        _buyGuideView = UIView()
        if let toastView = _buyGuideView{
            
            toastView.frame = CGRect(x: iSpace, y: qianli_pm_height + 10, width: toastWidth, height: toastHeight)
            self.view.addSubview(toastView)
            
            // 创建并添加倒三角形
            let triangle = P45gWVwQuFbDBrDN(width: 30, height: triangleHeight)
            triangle.position = CGPoint(x: toastWidth/2, y: toastHeight-triangleHeight-3)
            //CAShapeLayer 的 position 属性对应于其 anchorPoint（默认是 (0.5, 0.5)，即中心点），因此要让三角形居中，应该直接使用 toastWidth/2 作为 X 坐标
            triangle.fillColor = UIColor(hexString: "#fbfbfb").cgColor //UIColor.white.withAlphaComponent(0.85).cgColor
            toastView.layer.addSublayer(triangle)
            
            toastView.qianli_view_shadow(shadowColor: .label, offset: CGSize(width: 3, height: 3), opacity: 0.55, radius: 12)
            
            // 创建主内容区域（不含三角形）
            let contentView = UIView(frame: CGRect(x: 0, y: 0, width: toastWidth, height: toastHeight-triangleHeight))
            contentView.backgroundColor =  UIColor(hexString: "#fbfbfb") //.white.withAlphaComponent(0.85)
            contentView.layer.cornerRadius = 12
            contentView.clipsToBounds = true
            toastView.addSubview(contentView)
            
            let label = UILabel(frame: CGRect(x: 0, y: 0, width: toastWidth , height: contentView.bounds.height))
            contentView.addSubview(label)
            label.numberOfLines = 0
            label.adjustsFontSizeToFitWidth = true
            label.textColor = UIColor(hexString: "#aa5555");
            label.font = .systemFont(ofSize: 16)
            label.text = msg
            label.textAlignment = .center
            
            let vipViewTop = qianli_pm_height-140 //      vipView.Top = qianli_pm_height-140
            //usingSpringWithDamping传入数值为0.0~1.0,数值越大,弹性越不明显
            //initialSpringVelocity数值越大，初始速度越大
            UIView.animate(withDuration: 0.5, delay:0, usingSpringWithDamping: 0.4, initialSpringVelocity: 25, options: [.curveEaseInOut]) {
                toastView.frame = CGRect(x: iSpace, y: vipViewTop - toastHeight - 10, width: toastWidth, height: toastHeight+triangleHeight)
            }
            self.perform(#selector(iGO3AFqbPcS7YBzG), with: nil, afterDelay: 2);
        }
    }
    
    // 创建倒三角形的辅助方法
    private func P45gWVwQuFbDBrDN(width: CGFloat, height: CGFloat) -> CAShapeLayer {
        let path = CGMutablePath()
        path.move(to: CGPoint(x: -width/2, y: 0))
        path.addLine(to: CGPoint(x: width/2, y: 0))
        path.addLine(to: CGPoint(x: 0, y: height))
        path.closeSubpath()
        
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = path
        return shapeLayer
    }
    
    @objc private func iGO3AFqbPcS7YBzG(){
        if let toastView = _buyGuideView{
//            let iSpace = 30.0
//            let toastWidth = qianli_pm_width - iSpace*2
//            let triangleHeight = 15.0
//            let toastHeight = 80.0 + triangleHeight
//            self.UZelDtHZwCXcTj32()
            UIView.animate(withDuration: 0.25, delay: 0, options: [.curveEaseInOut]) {[weak toastView] in
                toastView?.alpha = 0
            } completion: { [weak self] _ in
                self?.UZelDtHZwCXcTj32()
            }
//         UIView.animate(withDuration: 0.25, delay:0, usingSpringWithDamping: 0.4, initialSpringVelocity: 25, options: [.curveEaseInOut]) {[weak toastView] in
//                toastView?.frame = CGRect(x: iSpace, y: qianli_pm_height+10, width: toastWidth, height: toastHeight)
//            } completion: {[weak self] _ in
//                self?.UZelDtHZwCXcTj32()
//            }
        }
        
    }
    
    private func UZelDtHZwCXcTj32(){
        NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(iGO3AFqbPcS7YBzG), object: nil)
        if let toastView = _buyGuideView{
            toastView.isHidden = true
            for perchild in toastView.subviews{
                perchild.removeFromSuperview()
            }
            toastView.removeFromSuperview()
        }
        _buyGuideView = nil
    }
}

extension QianMainWindowVC{
//打开节点列表页面
    func OdQ4QZH4IkFYy5fW(){
        DispatchQueue.main.async {[weak self] in
            self?.l0JOXR3PG9RznwqZ()
            
            if let self = self{
                let level = Defaults[\.memberLevel]
                let serverState = Defaults[\.serviceStatus]
                let subState = Defaults[\.subStatus]
                let isTester = false
                if level == 2 && serverState && subState && isTester{ //可以弃用
                    //判断shared/config是否存在，不存在则需要下载
                    let uuid = Qianli_G_SharedMdb.shared.GetSubUUID()
                    if uuid.isEmpty{
                        self.view.Qianli_Toast("\(LocalizedString("Proxy Node Error，Make sure Login & Retry"))[1]") //节点配置失效，请确认登录后重试
                        return
                    }
                    guard let homeDir = getSharedDir(udid: uuid,create: true) else{
                        self.view.Qianli_Toast("\(LocalizedString("Proxy Node Error，Make sure Login & Retry"))[2]")
                        return
                    }
                    
                    let target = homeDir.appendingPathComponent("config.yaml")
                    if !FileManager.default.fileExists(atPath: target.path){
                        self.view.Qianli_Toast("\(LocalizedString("Proxy Node Error，Make sure Login & Retry"))[3]")
                        return
                    }
                }
                
                let countryVC = QianliCountryVC()
                countryVC.modalPresentationStyle = .overFullScreen
                countryVC.dismissBlock = {[weak self] in
                    self?.zQvadXwaQRV67JmE()
                    self?.vOzKzS2HbOHZpSez("")
                }
                countryVC.invalid40101Block = {[weak self] errMsg in
                    DispatchQueue.main.async {
                        self?.flM9woQKzM3ymMZp(errMsg)
                    }
                }
                self.present(countryVC, animated: true)
            }
        }
    }
    private func DvET4H5IGpMq3MCT(_ title:String)->Bool{
        return (title.isEmpty || title == "Qianli.Ai.Router")
    }
    
    private func zQvadXwaQRV67JmE(){
        var title = Qianli_G_SharedMdb.shared.GetNodeName()
        if let lastNode = Qianli_G_SharedMdb.shared.lastQianliNodeTitle{
            if !lastNode.isEmpty{
                title = lastNode
            }
        }
        
        if let nlabel = self.Im8hl8CBwbpUKkwa{
            nlabel.text = self.DvET4H5IGpMq3MCT(title) ? LocalizedString("Auto Best Router") : title
        }
        if let nLogo = self.gqAAt48D69O3eb0V{
            let logoHeight = 40.0 * 4.0 / 6.0
            nLogo.frame = CGRect(x: 15, y: 60/2 - logoHeight/2, width: 40, height: logoHeight)
            
            if self.DvET4H5IGpMq3MCT(title){
                nLogo.image = "qianli_flag_auto".qianli_R_image
                nLogo.frame = CGRect(x: 15, y: 60/2 - 40/2, width: 40, height: 40)
            }
            else if(title.contains("巴西")){
                nLogo.image = "qianli_flag_bx".qianli_R_image
            }
            else if(title.contains("香港")){
                nLogo.image = "qianli_flag_xg".qianli_R_image
            }
            else if(title.contains("德国")){
                nLogo.image = "qianli_flag_dg".qianli_R_image
            }
            else if(title.contains("俄罗斯")){
                nLogo.image = "qianli_flag_els".qianli_R_image
            }
            else if(title.contains("法国")){
                nLogo.image = "qianli_flag_fg".qianli_R_image
            }
            else if(title.contains("韩国")){
                nLogo.image = "qianli_flag_hg".qianli_R_image
            }
            else if(title.contains("美国")){
                nLogo.image = "qianli_flag_mg".qianli_R_image
            }
            else if(title.contains("墨西哥")){
                nLogo.image = "qianli_flag_mxg".qianli_R_image
            }
            else if(title.contains("日本")){
                nLogo.image = "qianli_flag_rb".qianli_R_image
            }
            else if(title.contains("新加坡")){
                nLogo.image = "qianli_flag_xjp".qianli_R_image
            }
            else if(title.contains("印度")){
                nLogo.image = "qianli_flag_yd".qianli_R_image
            }
            else if(title.contains("英国")){
                nLogo.image = "qianli_flag_yg".qianli_R_image
            }
            else if(title.contains("英国")){
                nLogo.image = "qianli_flag_yg".qianli_R_image
            }
            else if(title.contains("巴基斯坦")){
                nLogo.image = "qianli_flag_bjst".qianli_R_image
            }
            else if(title.contains("迪拜")){
                nLogo.image = "qianli_flag_db".qianli_R_image
            }
            else if(title.contains("菲律宾")){
                nLogo.image = "qianli_flag_flb".qianli_R_image
            }
            else if(title.contains("马来西亚")){
                nLogo.image = "qianli_flag_mlxy".qianli_R_image
            }
            else if(title.contains("泰国")){
                nLogo.image = "qianli_flag_tg".qianli_R_image
            }
            else if(title.contains("西班牙")){
                nLogo.image = "qianli_flag_xby".qianli_R_image
            }
            else if(title.contains("意大利")){
                nLogo.image = "qianli_flag_ydl".qianli_R_image
            }
            else if(title.contains("印尼") || title.contains("印度尼西亚")){
                nLogo.image = "qianli_flag_yn".qianli_R_image
            }
            else if(title.contains("台湾")){
                nLogo.image = "qianli_flag_tw".qianli_R_image
            }
            else if(title.contains("自动")){
                nLogo.image = "qianli_qianli_flag_auto".qianli_R_image
            }
            else{
               nLogo.image = "qianli_flag_default".qianli_R_image
            }
        }
    }
    
}


extension QianMainWindowVC{
    func iyDeSaPKCzr5f6dG(){
        NotificationCenter.default.addObserver(self, selector: #selector(fJHiEw19ZnHmqqM7), name: UIApplication.didBecomeActiveNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(sklgIHYrI4h4rbcM), name: UIApplication.didEnterBackgroundNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(Aop4Q3vDdMQzDyeS), name: UIApplication.willTerminateNotification, object: nil)
      
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(rCKx6WfdkUurluw4(_:)),
            name: Notification.Name("CrashMonitorDidDetectCrashNotification"),
            object: nil
        )
        S8lrlnUkqz5Wyq55(true)
    }
//首次启动(在viewDidAppear前触发) or 后台切换到前台
    @objc func fJHiEw19ZnHmqqM7(notification: NSNotification) {
        if(self.isViewLoaded){
            QianliUniversalFunc.QianliLog("applicationDidBecomeActive")
            A8tW2HCNHpyKoNzc((_runningState == .connected),true)
        }
        
        if (self.MRXkpv4MdQ01tlAa){
            let hasAllowed = Defaults[\.hasAllowedPolicy]
            if hasAllowed{
                let token = Defaults[\.token]
                if token.isEmpty{
                    self.PBw1Iq57b3Be0LKP(0.5)
                }else{
                    self.vOzKzS2HbOHZpSez("")
                    self.perform(#selector(Gqb3bbCfe165tG09), with: nil, afterDelay: 0.5)
                }
            }
            self.feZMYC8LMPCfHkeY()
        }
    }
    
    @objc func sklgIHYrI4h4rbcM(notification: NSNotification) {
        QianliUniversalFunc.QianliLog("applicationEnterBackground")
        self.gKYhtPoiW44r45Cr()
    }
    
    @objc func Aop4Q3vDdMQzDyeS(){
        NotificationCenter.default.removeObserver(self)
        QianliUniversalFunc.QianliLog("terminateApp.now")
    }
    
    
    // 步骤3：处理上次崩溃信息
    @objc func rCKx6WfdkUurluw4(_ notification: Notification) {
        guard let crashInfo = notification.userInfo as? [String: Any] else { return }
        
        // 示例1：打印崩溃信息
        print("上次崩溃详情：")
        print("类型：\(crashInfo["type"] ?? "未知")")
        print("原因：\(crashInfo["reason"] ?? crashInfo["signal"] ?? "未知")")
        print("堆栈：\(crashInfo["stack"] ?? "无")")
        
        
        // 示例2：上传到服务器
        QpxpeqdYjfKXXRiz(crashInfo)
        
        self.perform(#selector(TWSIbTPvZq5VZno2), with: nil, afterDelay: 3.0)
        // 示例3：弹窗提示用户
//        showCrashAlert(crashInfo)
//      self.view.Qianli_Toast("onLastCrashDetected>\(crashInfo["type"] ?? "未知")-\(crashInfo["reason"] ?? crashInfo["signal"] ?? "未知")",delayTime: 10)
    }
    
    @objc func TWSIbTPvZq5VZno2(){
        self.view.Qianli_Toast("检测上次有异常退出\n如有任何问题,请联系客服!",delayTime: 3.0)
    }
    
    // 上传崩溃日志到服务器
    func QpxpeqdYjfKXXRiz(_ crashInfo: [String: Any]) {
        // 假设 crashInfo 是从通知中获取的字典
     
        var stackString  = "Null"
        if let stackArray = crashInfo["stack"] as? [String] {
            stackString = stackArray.joined(separator: "\n")
            if let base64Stack = stackString.data(using: .utf8)?
                .base64EncodedString(){
                stackString = base64Stack
            }else{
                // 对字符串进行 URL 编码
                stackString = "base64Fail"
                if stackArray.count>7 {
                    if let str = stackArray[7] as String?{
                        //7   todoios.debug.dylib                 0x00000001062b8344 $s7todoios14ViewControllerC7doProxyyyF + 224
                        if let encodedStr = str.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
                            stackString = encodedStr
                        }
                    }
                }
            }
        }
        
        let eventData = ["event":"lastCrash","error":"crash","carshtype":crashInfo["type"] ?? "未知",
                         "reason":crashInfo["reason"] ?? crashInfo["signal"] ?? "未知","stack":stackString]
        print("uploadCrashToServer>eventData:\n",eventData)
        
        ZacollectModel.shared.vnveDBhaItvpywSl(eventDict: eventData)
    }
    
    
    
}


extension QianMainWindowVC:UITextViewDelegate{
    
    private func oN0G5xzbIHJAiKYz(){
        self.zzSlxOdRaR1Kvn6l = Defaults[\.lastJKouUrlIndex]
        
        let hasAllowedPolicy = Defaults[\.hasAllowedPolicy]
        if hasAllowedPolicy{
            self.PBw1Iq57b3Be0LKP(0.5)
            return
        }
        
        let alertbgView = UIView(frame: CGRect(x: 0, y: 0, width: qianli_pm_width, height: qianli_pm_height))
        self.view.addSubview(alertbgView)
        alertbgView.backgroundColor = .black.withAlphaComponent(0.6)
        
        // 获取系统当前使用的语言代码
//        if let preferredLang = Locale.preferredLanguages.first {
//            print("当前首选语言：\(preferredLang)") //  "en" 或 "zh-Hans-CN"
//        }

        // 获取应用最终使用的本地化语言（考虑所有优先级）
        let currentLang = Bundle.main.preferredLocalizations.first ?? "en"
        print("Localizable：\(currentLang)") //en 或 zh-Hans
        
        let dlg_h = (currentLang == "en") ? 460.0 : 360.0
        let dlg_w = 360.0
        let dlgView = UIView(frame: CGRect(x: qianli_pm_width/2 - dlg_w/2, y: qianli_pm_height/2-dlg_h/2-30, width: dlg_w, height: dlg_h))
        alertbgView.addSubview(dlgView)
        dlgView.backgroundColor = .secondarySystemBackground
        dlgView.layer.cornerRadius = 6
        
        let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: dlg_w, height: 60))
        dlgView.addSubview(titleLabel)
        titleLabel.font = .boldSystemFont(ofSize: 15)
        titleLabel.textColor  = .label
        titleLabel.text = LocalizedString("Friendly Reminder")

        titleLabel.textAlignment = .center
        
        let textView = UITextView(frame: CGRect(x: 15, y: 60, width: dlg_w-30, height: dlg_h-60-48))
        textView.isEditable = false
        textView.isSelectable = true //为true才能触发点击链接
        textView.delegate = self
        textView.font = .systemFont(ofSize: 13)
        textView.backgroundColor = .clear
        textView.textColor = .secondaryLabel
        dlgView.addSubview(textView)
        
        let welcomstr = LocalizedString("Welcome to Qianli Accelerator!")
        let wehave = LocalizedString("We value your privacy and are committed to protecting your personal data.")
        let before = LocalizedString("Before using this app, please confirm that you have read and agree to our Privacy Policy and Terms of Service.")
        let keypoint = LocalizedString("Key points include but are not limited to:")
        let point1 = LocalizedString("We do not log your browsing content or connection history.")
        let point2 = LocalizedString("All data transmissions are encrypted for security.")
        let point3 = LocalizedString("To optimize services, we may collect anonymous performance data (excluding personal information).")
        let clickto = LocalizedString("By clicking 'Agree & Continue' you accept these terms and can start securely connecting to the world.")
        let message = "\(welcomstr)\n\(wehave)\(before)\(keypoint)\n\(point1)\n\(point2)\n\(point3)\n\(clickto)\n"
//        let attributedMessage = NSMutableAttributedString(string: message)
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 8 // 设置行间距，可根据需要调整
//        attributedMessage.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: message.count))
//        attributedMessage.addAttributes([NSAttributedString.Key.paragraphStyle:paragraphStyle,
//                                         NSAttributedString.Key.foregroundColor: UIColor.secondaryLabel,//UIColor(hexString: "#3964ff"),
//                                         NSAttributedString.Key.font:UIFont.systemFont(ofSize: 13)], range: NSRange(location: 0, length: message.count))

        let myMutableString = NSMutableAttributedString(
                    string: message,
                    attributes: [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 13),
                                 NSAttributedString.Key.paragraphStyle:paragraphStyle,
                                 NSAttributedString.Key.foregroundColor:UIColor.secondaryLabel])
        let range_1:NSRange = (message as NSString).range(of:LocalizedString("SERVICE AGREEMENT")) //用户服务协议
        myMutableString.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.systemBlue,
                                       NSAttributedString.Key.link:URL(string: "action://userProtocol") as Any], range: range_1)
        
        let range_2:NSRange = (message as NSString).range(of:LocalizedString("PRIVACY POLICY"))
        myMutableString.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.systemBlue,
                                       NSAttributedString.Key.link:URL(string: "action://userPrivate") as Any], range: range_2)
        textView.attributedText = myMutableString
        
        let btnDisagree = UIButton(frame: CGRect(x: 0, y: dlg_h-48, width: dlg_w/2, height: 48))
        dlgView.addSubview(btnDisagree)
        btnDisagree.setTitle(LocalizedString("Disagree"), for: .normal)
        btnDisagree.setTitleColor(UIColor(hexString: "#3964ff"), for: .normal)
        btnDisagree.titleLabel?.font = .systemFont(ofSize: 15)
        btnDisagree.touch_With_Block { [weak self] sender in
            QianliVibrateEnum.error.L4smXfL531Hmh91R()
            self?.view.Qianli_Toast(LocalizedString("We need your consent to continue serving you!"))
        }
        let btnAgree = UIButton(frame: CGRect(x: dlg_w/2, y: dlg_h-48, width: dlg_w/2, height: 48))
        dlgView.addSubview(btnAgree)
        btnAgree.setTitle(LocalizedString("Agree & Continue"), for: .normal)
        btnAgree.setTitleColor(.white, for: .normal)
        btnAgree.titleLabel?.font = .systemFont(ofSize: 15)
        btnAgree.backgroundColor = UIColor(hexString: "#3964ff")
        btnAgree.qianli_round_rect(corner: [.bottomRight], radii: CGSize(width: 6, height: 6))
        btnAgree.touch_With_Block { [weak self,weak alertbgView] sender in
            Defaults[\.hasAllowedPolicy] = true
            QianliVibrateEnum.success.L4smXfL531Hmh91R()
            self?.view.Qianli_Toast(LocalizedString("Welcome to Qianli Accelerator!"))
            alertbgView?.isHidden = true
            if let alertbgview = alertbgView{
                for perview in alertbgview.subviews{
                    perview.removeFromSuperview()
                }
            }
            alertbgView?.removeFromSuperview()
            self?.a8PKVW0O8SiZSm0H()
        }
        let line = CALayer()
        dlgView.layer.addSublayer(line)
        line.frame = CGRect(x: 0, y: dlg_h-49, width: dlg_w, height: 0.5)
        line.backgroundColor = UIColor.lightGray.cgColor
        
        let lineV = CALayer()
        dlgView.layer.addSublayer(lineV)
        lineV.frame = CGRect(x: dlg_w/2, y: dlg_h-48, width: 0.5, height: 48)
        lineV.backgroundColor = UIColor.lightGray.cgColor
    }
    
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        if URL.absoluteString == "action://userProtocol" {
            GX2Ex29xLYziOn3d()
            return false
        }else if URL.absoluteString == "action://userPrivate" {
            A5emqwsTzcFhVbln()
            return false
        }
        return true
    }
    
    private func GX2Ex29xLYziOn3d(){
        QianliVibrateEnum.selection.L4smXfL531Hmh91R()
        if let url = URL(string: "https://help.qianli999.com/service-1.html"){
            let webpage = QainliProtocolWebPage(url: url,title: LocalizedString("SERVICE AGREEMENT"))//"服务协议"
            webpage.modalPresentationStyle = .overFullScreen
            self.present(webpage, animated: true)
        }
    }
    
    private func A5emqwsTzcFhVbln(){
        QianliVibrateEnum.selection.L4smXfL531Hmh91R()
        if let url = URL(string: "https://help.qianli999.com/privacy-1.html"){
            let webpage = QainliProtocolWebPage(url: url,title: LocalizedString("PRIVACY POLICY"))//"隐私政策"
            webpage.modalPresentationStyle = .overFullScreen
            self.present(webpage, animated: true)
        }
        
    }
}

